<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>定额选择</title>
    <!-- 引入其它组件 -->
    <!-- 引入 layui -->
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
    <style>
        .layui-table th,
        .layui-table td {
            border-color: green !important;
            /* 同时设置表头和单元格的边框颜色 */
        }

        .layui-table-cell-text {
            display: inline-block;
            max-width: 100%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 自定义高亮样式 */
        .layui-table tr.active-row {
            background-color: #f0f9eb !important;
        }

        .layui-table tr.active-row td {
            background-color: transparent !important;
        }
    </style>
</head>

<body>
    <div class="layui-card">
        <div class="layui-card-body" style="height: calc(100vh - 120px); display: flex; flex-direction: column;">
            <!-- 固定搜索栏 -->
            <div class="layui-form" style="flex-shrink: 0; padding-bottom: 10px;">
                <div class="layui-row" style="width:720px; display: flex; align-items: center;">
                    <div style="flex:1; margin-right: 10px;">
                        <input type="text" name="search" id="search-input" placeholder="输入定额编号/名称" class="layui-input"
                            lay-verify="search">
                    </div>
                    <div style="width:100px;">
                        <button class="layui-btn layui-btn-sm" id="btn-search">搜索</button>
                    </div>
                </div>
            </div>

            <!-- 可滚动的表格区域 -->
            <div style="flex-grow: 1;">
                <table id="quota-selector-table" lay-filter="quota-selector-table"></table>
            </div>
        </div>
    </div>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/layui/layui.js"></script>
    <script>
        layui.use(['table', 'jquery', 'form'], function () {
            var table = layui.table;
            var form = layui.form;
            var $ = layui.$;
            // 调试：检查token是否可用
            // console.log('iframe token:', localStorage.getItem('token'));

            var tableData = []; // 集中管理数据

            var isComposing = false;

            var itemCount = 0;

            // 初始化选择表格
            table.render({
                elem: '#quota-selector-table',
                id: 'quota-selector-table',
                height: 'full-80', // 自动高度减去150px（预留搜索栏空间）
                fixed: true, // 固定表头

                cols: [[
                    // { type: 'checkbox' },
                    { type: 'numbers', title: '序号', width: "48" },
                    { field: 'norm_code', title: '定额编号', width: "80" },
                    { field: 'norm_name', title: '项目名称', width: "360" },
                    { field: 'norm_unit', title: '单位', width: "80" },
                    { field: 'norm_mechanic', title: '技工', align: 'right', width: "60", templet: '<div class="layui-table-cell-number">{{ d.norm_mechanic.toFixed(2) }}</div>' },
                    { field: 'norm_general', title: '普工', align: 'right', width: "60", templet: '<div class="layui-table-cell-number">{{ d.norm_general.toFixed(2) }}</div>' },
                    { field: 'norm_content', title: '内容', templet: function (d) { return '<div class="layui-table-cell-text" title="' + d.norm_content + '">' + d.norm_content + '</div>' } },
                ]],
                data: { norm_code: '' }, // 通过AJAX加载
                page: false,
                defaultToolbar: [],
                size: 'sm',
                done: function (res) {

                    // 移除默认的hover背景色（可选）
                    $('.layui-table-body tr').hover(
                        function () { $(this).addClass('layui-bg-cyan'); },
                        function () { $(this).removeClass('layui-bg-cyan'); }
                    );

                    // 双击行事件
                    $('.layui-table-body tr').on('dblclick', function () {
                        var index = $(this).data('index');
                        var rowData = table.cache['quota-selector-table'][index]; // 正确获取行数据

                        // 阻止事件冒泡
                        var event = window.event || arguments.callee.caller.arguments[0];
                        if (event) event.stopPropagation();

                        // 调用输入框
                        InputCount(rowData);
                    });
                }
            });

            // 数据加载函数（替代done回调）
            function loadData(url) {
                // 使用封装好的http方法而不是$.get
                http.get(url)
                    .then(function (res) {
                        tableData = res.data;
                        filterData();
                    })
                    .catch(function (err) {
                        layer.msg('加载定额数据失败: ' + (err.message || err.msg), { icon: 2 });
                        console.error('API错误:', err);
                    });
            }

            // 筛选函数
            function filterData(keyword = '') {
                var filtered = keyword ?
                    tableData.filter(item => item.norm_name.includes(keyword)) :
                    tableData;

                table.reload('quota-selector-table', {
                    data: filtered, // 关键：只更新数据
                    page: false
                });
            }

            // 输入法状态监听
            layui.$('#search-input')
                .on('compositionstart', function () {
                    isComposing = true;
                })
                .on('compositionend', function () {
                    isComposing = false;
                    filterData($(this).val());
                })
                .on('input', function () {
                    if (!isComposing) filterData($(this).val());
                });

            function InputCount(rowData) {
                http.get(API_CONFIG.ENDPOINTS.GET_NORM_CONVERSION + '?normcode=' + rowData.norm_code)
                    .then(function (res) {
                        var options = res.data;

                        layer.open({
                            type: 1,
                            title: "定额：" + rowData.norm_name,
                            content: `
                            <div class="layui-form" style="padding:10px;">
                                <div class="layui-form-item">
                                    <!-- 数量输入框 -->
                                    <div class="layui-input-group" style="margin-bottom: 15px;">
                                        <div class="layui-input-prefix" style="width:80px;">设计数量</div>
                                        <input type="number" lay-affix="number" id="inputQuantity" min="0.01" step="0.01" lay-precision="2" class="layui-input">
                                        <div class="layui-input-suffix" style="width:80px; text-align:left;">${rowData.norm_unit || '个'}</div>
                                    </div>
                                    
                                    <!-- 调整选项（根据是否有选项决定显示） -->
                                    ${options && options.length > 0 ? `
                                    <div class="layui-input-group" style="margin-bottom: 15px;">
                                        <div class="layui-input-prefix" style="width:80px;">调整选项</div>
                                        <div class="layui-input-block" style="margin-left: 90px; padding-top: 5px;">
                                            ${options.map(opt => `<input type="checkbox" name="optionSelect" value="${opt.id}" title="${opt.name}" lay-skin="primary">`).join('')}
                                        </div>
                                    </div>`
                                    :
                                    `
                                    <div class="layui-form-item">
                                        <div class="layui-input-block" style="margin-left: 0;">
                                            <div class="layui-form-mid layui-word-aux">该项目无调整选项</div>
                                        </div>
                                    </div>`}
                                </div>

                                <!-- 备注文字输入框 -->
                                <div class="layui-form-item" style="margin-left:10px;margin-right:10px;">
                                    <textarea class="layui-textarea" placeholder="备注施工说明" style="margin-top: 10px;" id="inputRemark"></textarea>
                                </div>
                            </div>`,
                            // lay-verify="number|integer" 验证数字为整数
                            btn: ['确认', '取消'],
                            area: ['480px', '380px'],
                            success: function (layero, index) {
                                this.layero = layero;
                                layero.find('#inputQuantity').focus();
                                layui.form.render();
                                $('#inputQuantity').on('keypress', function (e) {
                                    if (e.keyCode === 13) $('.layui-layer-btn0').click();
                                });
                            },
                            yes: function (index) {
                                // 确认逻辑...
                                var layero = this.layero;
                                var quantity = parseFloat($('#inputQuantity').val());
                                var selectedConversions = [];

                                layero.find('input[name="optionSelect"]:checked').each(function () {
                                    var optionId = $(this).val();
                                    var selectedConversion = options.find(opt => opt.id == optionId);
                                    if (selectedConversion) {
                                        selectedConversions.push(selectedConversion);
                                    }
                                });

                                var remark = $('#inputRemark').val() + " <" + selectedConversions.map(opt => opt.name).join('、') + ">";

                                if (isNaN(quantity)) {
                                    layer.msg('请输入有效数字', { icon: 2 });
                                    $('#inputQuantity').focus();
                                    return false;
                                }

                                var resultData = {
                                    ...rowData,
                                    quantity: quantity,
                                    conversions: selectedConversions,
                                    remark: remark,
                                    mechanics: (rowData.norm_mechanic * quantity).toFixed(2),
                                    generals: (rowData.norm_general * quantity).toFixed(2),
                                };

                                layer.close(index);

                                if (parent && parent.layui) {
                                    parent.handleNormSelect(resultData);
                                }
                            }
                        });
                    })
                    .catch(function (err) {
                        layer.msg('加载选项数据失败: ' + (err.message || err.msg), { icon: 2 });
                        console.error('API错误:', err);
                    });
            }

            loadData(API_CONFIG.ENDPOINTS.GET_NORM_LABOR);
        });

    </script>

</body>

</html>